package com.iot08.api.service;

import com.iot08.common.entity.app.PxAdverster;
import com.iot08.common.service.base.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


/**
 * @author cwj
 * @description
 * @date 2025/4/14 14:10
 **/
@Slf4j
@Service
public class PxAdversterService extends BaseService<PxAdverster> {


    /**
     * @description 根据shortName查询广告商
     * @author cwj
     * @param [shortName]
     * @return com.iot08.common.entity.app.PxAdverster
     * @date @time 2025/4/14 14:18
     **/
    public PxAdverster queryAdversterByShortName(String shortName){
        Query query = new Query(Criteria.where("shortName").is(shortName).and("status").is(1)).limit(1);
        return this.findOne(query);
    }

    /**
     * @description 根据权重和优先级筛选广告商
     * @author cwj
     * @param []
     * @return com.iot08.common.entity.app.PxAdverster
     * @date @time 2025/4/14 14:38
     **/
    public PxAdverster queryAdversterByWeightPriority(){
        Query query = new Query(Criteria.where("status").is(1));
        List<PxAdverster> pxAdversters = this.find(query);
        PxAdverster pxAdverster = null;
        if(!CollectionUtils.isEmpty(pxAdversters)){
            if(pxAdversters.size() == 1){
                pxAdverster = pxAdversters.get(0);
            } else {
                double totalScore = pxAdversters.stream().mapToDouble(PxAdverster::getScore).sum();
                double rand = Math.random() * totalScore;
                double running = 0;
                for (PxAdverster ad : pxAdversters) {
                    running += ad.getScore();
                    if (rand <= running) {
                        pxAdverster = ad;
                        break;
                    }
                }
            }
        }
        return pxAdverster;
    }



}
